package com.lianxian.xindong.login.mvp.presenter;

import android.app.Application;
import android.content.Intent;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hxb.library.integration.AppManager;
import com.hxb.library.di.scope.ActivityScope;
import com.hxb.library.mvp.BasePresenter;
import com.hxb.library.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;

import javax.inject.Inject;

import com.hxb.library.utils.RxLifecycleUtils;
import com.lianxian.xindong.commonres.observer.MyHttpResultObserver;
import com.lianxian.xindong.commonsdk.BuildConfig;
import com.lianxian.xindong.commonsdk.core.RouterHub;
import com.lianxian.xindong.login.mvp.contract.LoginPhoneContract;
import com.lianxian.xindong.login.mvp.model.entity.RequestLoginUserBean;
import com.lianxian.xindong.login.mvp.ui.activity.LoginOtherActivity;
import com.lianxian.xindong.login.mvp.ui.activity.RegisterActivity;


/**
 * @作者：hexingbo
 * @时间：06/30/2023
 * @描述：
 */
@ActivityScope
public class LoginPhonePresenter extends BasePresenter<LoginPhoneContract.Model, LoginPhoneContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public LoginPhonePresenter(LoginPhoneContract.Model model, LoginPhoneContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    private boolean agree;

    /**
     * 是否同意协议
     *
     * @param agree
     */
    public void checkAgreement(boolean agree) {
        this.agree = agree;
    }

    /**
     * 提交登录参数
     *
     * @param phone    手机号
     * @param password 登录密码
     */
    public void submitLoginData(String phone, String password) {
        if (!agree) {
            mRootView.showMessage("请阅读并同意协议");
            return;
        }

        if (TextUtils.isEmpty(phone) || phone.length() != 11) {
            mRootView.showMessage("请输入11位手机号");
            return;
        }
        if (TextUtils.isEmpty(password) || password.length() < 6) {
            mRootView.showMessage("请输入不少于6位密码");
            return;
        }

        if (true) {
            goAppMainActivityAndKillMyself();
            return;
        }

        //请求服务器数据
        RequestLoginUserBean loginUserBean = new RequestLoginUserBean("手机号登录");
        loginUserBean.setLoginPhoneData(phone, password);
        mModel.getLoginUser(loginUserBean)
                .subscribeOn(Schedulers.io())
                .retryWhen(new RetryWithDelay(
                        //遇到错误时重试,第一个参数为重试几次,第二个参数为重试的间隔
                        BuildConfig.HTTP_MaxRetries, BuildConfig.HTTP_RetryDelaySecond))
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();
                })
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new MyHttpResultObserver<String>(mErrorHandler) {

                    @Override
                    public void onResult(String result) {
                        if (TextUtils.isEmpty(result)) {
                            mRootView.showMessage("登录失败");
                        } else {
                            goAppMainActivityAndKillMyself();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                    }
                });
    }

    /**
     * 跳转主界面,并关闭当前页面
     */
    public void goAppMainActivityAndKillMyself() {
        ARouter.getInstance()
                .build(RouterHub.APP_MAINACTIVITY)
                .navigation(mApplication);
        mRootView.killMyself();
    }

    /**
     * 注册用户信息
     */
    public void goRegisterInfo() {
        mRootView.launchActivity(new Intent(mRootView.getContext(), RegisterActivity.class));
        mRootView.killMyself();
    }

    /**
     * 切换登录方式
     */
    public void changeLoginType() {
        mRootView.launchActivity(new Intent(mRootView.getContext(), LoginOtherActivity.class));
        mRootView.killMyself();
    }
}
